/**
 * 转账页面
 */
import {
  transfer,
  userAuth,
  getAccountInfo,
  getAllAccountInfo,
} from  '/common/api';

const app = getApp();

Page({
  data: {
    loading: false,
    showNotice: false,
    amountLimit: 0,
    amount: 0,
    allAccounts: [],
    accountsIndex: -1,
  },

  onLoad() {
    this.userAuthLogin();
    // 接收websocket消息
    app.globalData.onSocketMessage = this.onSocketMessage.bind(this);
  },

  onShow() {
    this.handleGetAccountInfo();
  },

  // 授权登录
  userAuthLogin() {
    my.getAuthCode({
      scopes: 'auth_user',
      success: (res) => {
        my.showLoading();
        const { authCode } = res;
        userAuth(authCode)
          .then(({ data: res }) => {
            my.hideLoading();
            if (res.message === 'success') {
              const { userId } = res.data;
              my.setStorageSync({
                key: 'userId',
                data: userId,
              });
              this.handleGetAccountInfo();
              this.handleGetAllAccountInfo();
              app.handleConnectSocket();
            } else {
              const { data: content } = res;
              my.showToast({
                type: 'fail',
                content,
              });
            }
          }).catch((err) => {
            console.log(err);
          });
      },
      fail: () => {
        my.confirm({
          title: '提示',
          content: '必须授权登录才可继续操作，是否重新授权？',
          success: (res) => {
            if (res.confirm) {
              this.userAuthLogin();
            }
          }
        });
      }
    });
  },

  // 提交转账
  handleSubmit(e) {
    const { amount } = e.detail.value;
    const { accountsIndex, allAccounts } = this.data;
    if (!this.verificationForm(accountsIndex, amount)){
      return;
    }
    const account = allAccounts[accountsIndex].userId;
    this.setData({
      loading: true,
    });
    transfer(account, amount)
      .then(({data: res}) => {
        this.setData({
          loading: false,
        });
        if (res.message === 'success') {
          this.handleToResult(amount);
        } else {
          const { data: content } = res;
          my.showToast({
            type: 'fail',
            content,
          });
        }
      }).catch((err) => {
        console.log(err);
      });
  },

  // 表单验证
  verificationForm(accountsIndex, amount) {
    if (!(accountsIndex !== -1 && amount)) {
      my.showToast({
        type: 'fail',
        content: '账户和金额不得为空',
      });
      return false;
    }
    if (isNaN(Number(amount))) {
      my.showToast({
        type: 'fail',
        content: '转账金额必须为数字',
      });
      return false;
    }
    if (this.data.amountLimit !== null && Number(amount) > this.data.amountLimit) {
      my.showToast({
        type: 'fail',
        content: '转账金额不得超过转账限额',
      });
      return false;
    }
    return true;
  },

  // 查看交易记录
  handleToRecord() {
    my.navigateTo({
      url: '/pages/record/record',
    });
  },

  // 跳转转账结果页面
  handleToResult(amount) {
    my.navigateTo({
      url: `/pages/result/result?amount=${amount}`,
    });
  },

  onSocketMessage(res) {
    const { data } = res;
    const message  = JSON.parse(data);
    if (message.type) {
      this.setData({
        showNotice: true,
      });
      my.setStorageSync({
        key: 'messageData',
        data,
      });
    }
  },

  // 查看消息
  linkClick() {
    this.setData({
      showNotice: false,
    });
    my.switchTab({
      url: `/pages/message/message?messageData=${this.messageData}`,
    });
  },

  // 获取账户信息
  handleGetAccountInfo() {
    const { data: userId } = my.getStorageSync({
      key: 'userId',
    });
    if (userId) {
      getAccountInfo()
        .then(({ data: res}) => {
          if (res.message === 'success') {
            const { amountLimit, amount } = res.data;
            this.setData({
              amountLimit,
              amount,
            });
          } else {
            const { data: content } = res;
            my.showToast({
              type: 'fail',
              content,
            });
          }
        }).catch((err) => {
          console.log(err);
        }); 
    }
  },

  // 获取所有账户信息
  handleGetAllAccountInfo() {
    getAllAccountInfo()
      .then(({ data: res}) => {
        if (res.message === 'success') {
          const userId = my.getStorageSync({
            key: 'userId',
          }).data;
          const allAccounts = res.data.filter((item) => {
            return item.userId !== userId;
          });
          this.setData({
            allAccounts,
          });
        } else {
          const { data: content } = res;
          my.showToast({
            type: 'fail',
            content,
          });
        }
      }).catch((err) => {
        console.log(err);
      });
  },

  bindPickerChange(e) {
    this.setData({
      accountsIndex: e.detail.value,
    });
  }
});
